define([
	'jquery',
	'underscore',
	'backbone',
	'baseView',
	'text!o2o/role/add.html',
	'js/myUtil.js'
], function($, _, Backbone, BaseView, tpl, myUtil) {
	return BaseView.extend({
		render: function(cb) {
			var that = this;
			var nodeTip = $(this.el).find('.tip');
			nodeTip.hide();

			myUtil.getAllPermissions(function(err, res) {
				console.log('getAllPermissions res', res);
				if (err) return nodeTip.text(err).show();
				if (res.errCode !== 0) return nodeTip.text(res.errMsg).show();

				var tmpl = _.template(tpl);
				var tmpl2 = tmpl({
					list: res.result
				})
				$(that.el).html(tmpl2);
				if (!$(this.el).is(":visible")) // if hide then show
					that.show();
				cb && cb();
			});
		},

		events: {
			"submit #addRole": "doAddRole"
		},

		doAddRole: function(event) {
			event.preventDefault();
			var formData = $('form#addRole').serializeObject();
			console.log(formData);
			var nodeTip = $(this.el).find('.tip');
			nodeTip.hide();

			// TODO check local
			myUtil.addRole(formData, function(err, res) {
				console.log(res);
				if (err) return nodeTip.text(err).show();
				if (res.errCode !== 0) return nodeTip.text(res.errMsg).show();

				// all sucess;
				console.log('succ');
				window.location.href = "#o2o/role/";
			});
		}
	});
});